package org.yray.sip.rtp.sender;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.yray.sip.server.SipSession;
import org.yray.sip.time.OffPauseSendTask;
import org.yray.sip.time.SendMediaSendTask;
import org.yray.sip.time.SendPacketTimer;
import org.yray.sip.utils.IcspBeanHolder;

@Data
@Slf4j
public class RtRtpTts {

    private int timeStamp;
    private int len;
    private long correction;
    private long curr;
    private long time;
    private long currNanos;
    private int sentenceSn;
    private SipSession session;


    public RtRtpTts(SipSession session)
    {
        this.timeStamp=session.getTimeStamp();
        this.len=0;
        this.correction=SipSession.PCMA_STEP_TIME_LEN-session.getSendRRTime()%SipSession.PCMA_STEP_TIME_LEN;
        this.curr=System.currentTimeMillis();
        this.currNanos=System.nanoTime();
        this.time=0;
        this.sentenceSn=session.incSentenceSnAndGet();
        this.session=session;
    }

    public synchronized void addWav(byte[] wavs)
    {
        int currLen= wavs.length/ SipSession.PCMA_STEP_SIZE;
        log.info("bs len={}",len);
        for(int i=0;i<currLen;i++) {
            byte[] bsRtp = new byte[SipSession.PCMA_STEP_SIZE];
            System.arraycopy(wavs,i*SipSession.PCMA_STEP_SIZE,bsRtp,0,SipSession.PCMA_STEP_SIZE);
            byte[] sendPcms=RtpPacket.builtPcma(session.getSsrc(), session.getRtpSeq(), timeStamp, bsRtp);
            time=(i+len)*SipSession.PCMA_STEP_TIME_LEN+correction+curr;
            //time=((i+len)*SipSession.PCMA_STEP_TIME_LEN+correction)*1000000+currNanos;
            getTimer().add(new SendMediaSendTask(time,sendPcms,session.mySideRtpSender(),i+len,sentenceSn,session.getCallId()));
            timeStamp+=SipSession.PCMA_STEP_STAMP;
        }
        len+=currLen;
    }

    public synchronized int finish()
    {
        getTimer().add(new OffPauseSendTask(time+20,session.getCallId()));
        return len*SipSession.PCMA_STEP_TIME_LEN;
    }


    private SendPacketTimer getTimer()
    {
       return IcspBeanHolder.getBean(SendPacketTimer.class);
    }
}
